﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;

namespace BigFileUploadDemo.Lib
{
    public static class RedisConfigure
    {
        /// <summary>
        /// redis配置
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void ConfigureRedis(this IServiceCollection services, IConfiguration configuration)
        {
            string redisMode = configuration.GetSection("RedisOption:Mode").Value;
            if (redisMode == "cluser")
                UseRedisSentienl(configuration);
            else
                UseRedisSingle(configuration);
        }
        public static IDatabase db;
        public static string DefaultKey = ConfigurationHelper.GetSectionValue("Redis.DefaultKey");

        public static void UseRedisSentienl(IConfiguration configuration)
        {
            ConfigurationOptions sentinelOptions = new ConfigurationOptions();
            string[] sentinels = configuration.GetSection("RedisOption:SentinelNodes").Value.Split(',');
            foreach (string sentinel in sentinels)
            {
                sentinelOptions.EndPoints.Add(sentinel);
            }

            sentinelOptions.TieBreaker = "";
            sentinelOptions.CommandMap = CommandMap.Sentinel;
            sentinelOptions.AbortOnConnectFail = false;
            // Connect!
            ConnectionMultiplexer sentinelConnection = ConnectionMultiplexer.Connect(sentinelOptions);

            // Get a connection to the master
            //通过配置文件，需按照官方给出的配置格式 https://stackexchange.github.io/StackExchange.Redis/Configuration
            ConfigurationOptions redisServiceOptions = ConfigurationOptions.Parse(configuration.GetSection("RedisOption:SentinelService").Value);
            //直接配置
            //ConfigurationOptions redisServiceOptions = new ConfigurationOptions();
            //redisServiceOptions.ServiceName = "mymaster";   //master名称
            //redisServiceOptions.Password = "magicloud666";     //master访问密码
            //redisServiceOptions.DefaultDatabase = 7;
            //redisServiceOptions.AbortOnConnectFail = true;
            ConnectionMultiplexer masterConnection = sentinelConnection.GetSentinelMasterConnection(redisServiceOptions);

            db = masterConnection.GetDatabase();


        }

        public static void UseRedisSingle(IConfiguration configuration)
        {
            var masterConnection = ConnectionMultiplexer.Connect(configuration.GetSection("RedisOption:Single").Value);
            db = masterConnection.GetDatabase();
        }
    }
}
